#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#include "map.h"
#include "ship.h"
#include "direction.h"

Map *g_map = NULL;
Ship *g_ships = NULL;
Ship *g_select_ship = 0;
int g_wind_direction = DIR_UP_RIGHT;

const int g_num_ships = 20;

/* check if map already have ship */
int TestPlace(int x, int y, int n) {
    int i;
    for (i = 0; i < n; ++i) {
        if ((g_ships + i)->x == x && (g_ships + i)->y == y)
            return 0;
    }
    return 1;
}

void InitMap(int w, int h) {
    g_map = calloc(1, sizeof(Map));
    g_map->w = w;
    g_map->h = h;
    g_map->buffer = calloc(w * h, sizeof(char));

    g_ships = calloc(g_num_ships, sizeof(Ship));


    srand(time(NULL));

    int i;
    for (i = 0; i < g_num_ships; ++i) {
        Ship *ship = g_ships + i;
        int x;
        int y;

        do {
            x = rand() % w;
            y = rand() % h;
        } while (!TestPlace(x, y, i));

        InitShip(ship, x, y);
    }
}

void DestroyMap() {
    if (g_map) {
        if (g_map->buffer) {
            free(g_map->buffer);
            g_map->buffer = NULL;
        }
        free(g_map);
        g_map = NULL;
    }

    if (g_ships) {
        free(g_ships);
        g_ships = NULL;
    }
}

void DumpMap() {
    int i;
    for (i = 0; i < g_num_ships; ++i) {
        Ship* ship = g_ships + i;
        printf("ship[%d] = { %d, %d}\n", i, ship->x, ship->y);
    }
}

int IsOnMap(int x, int y) {
    return x >= 0 && y >= 0 && x < g_map->w && y < g_map->h;
}

Ship* ShipOnMap(int x, int y) {
    int i;
    for (i = 0; i < g_num_ships; ++i) {
        Ship* ship = g_ships + i;
        if (ship->x == x && ship->y == y)
            return ship;
    }

    return 0;
}

void OffsetToCoords(int *x_res, int *y_res,  int x, int y, int direction, int len) {
    *x_res = x;
    *y_res = y;
    switch (direction) {
        case DIR_UP:
            *x_res -= len;
            *y_res += len;
            break;
        case DIR_UP_RIGHT:
            *y_res += len;
            break;
        case DIR_RIGHT:
            *x_res += len;
            *y_res += len;
            break;
        case DIR_DOWN_RIGHT:
            *x_res += len;
            break;
        case DIR_DOWN:
            *x_res += len;
            *y_res -= len;
            break;
        case DIR_DOWN_LEFT:
            *y_res -= len;
            break;
        case DIR_LEFT:
            *x_res -= len;
            *y_res -= len;
            break;
        case DIR_UP_LEFT:
            *x_res -= len;
            break;
    }
}
